<template>
  <div style="display: flex;align-items: flex-end;flex-direction: column">
    <div style="width: 100%;display: flex;align-items: center;flex-direction: row;justify-content: space-between;">
      <div></div>
<!--      <el-button class="btn-seal" type="primary" @click="exportExcel">Download</el-button>-->
<!--      v-if="apiKey!='browse'"-->
      <el-input
          v-model="search"
          style="max-width: 200px;margin: 5px 0;"
          placeholder="Please input"
      >
        <template #append>
          <el-button @click="searchTable">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
<!--      <div v-else>-->
<!--        <br>-->
<!--        <br>-->
<!--      </div>-->
    </div>
    <el-table
        id="educe-table"
        v-loading="tableloading"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ 'text-align' : 'center', 'color' : 'black'}"
        :data="tableData"
        :row-class-name="tableRowClassName"
        header-row-class-name="table-header-row"
        header-cell-class-name="table-header-cell"
        header-row-style="font-size: 18px;"
        border
        stripe
        :default-sort="{ prop: 'date', order: 'descending' }"
    >
      <el-table-column
          v-for="item in column"
          sortable
          :prop="item.value"
          :label="item.name"
          :width="item.width"
          :render-header="renderHeader"
          header-align="center"
          show-overflow-tooltip
          resizable
      >
        <template #default="{row}" v-if="item.href">
          <el-button link style="color: #337ab7" @click="toDetail(row['asmid'],row['idInDbsnp'])">{{ row[item.value]}}</el-button>
        </template>
        <template #default="{row}" v-if="item.value == 'selectTf'">
          {{searchKey.tf}}
        </template>
        <template #default="{row}" v-if="item.value == 'selectMotif'">
          {{searchKey.motif_id}}
        </template>
      </el-table-column>
  <!--    <el-table-column v-for="item in column" sortable :prop="item.value" :label="item.name"></el-table-column>-->
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        style="margin: 5px 0"
        :page-size="size"
        :total="total"
        :current-page="currentPage"
        @current-change="handlePageChange"
    />
  </div>
</template>

<script>
import {useRouter} from "vue-router";
import {useRoute} from "vue-router";
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx';
import api from "@/api/api";

export default {
  name: "table",
  data(){
    return {
      search:'',
      tableloading: true,
      tableData: [],
      tableAllData: [],
      total: 0,

      currentPage:1,
      rsList: []
    }
  },
  props:{
    searchKey: {
      type: String,
      required: false,
      default: ''
    },
    apiKey:{
      type: String,
      required: false,
      default: ''
    },
    column:{
      type: Array,
      required: true,
      default: []
    },
    size:{
      type: Number,
      required: false,
      default: 14
    },
  },
  watch:{
    tableAllData: {
      handler (newValue, oldValue) {
        console.log('tableAllData==>',newValue)
        Reflect.set(this,'tableloading',true)
        Reflect.set(this,'tableAllData',newValue)
        this.gettabledataFirst()
        console.log('tableAllData==>ok')
      }
    },
    searchKey: {
      handler (newValue, oldValue) {
        console.log('searchKey==>',newValue)
        Reflect.set(this,'tableloading',true)
        Reflect.set(this,'searchKey',newValue)
        this.gettabledataFirst()
        console.log('searchKey==>ok')
      }
    },
    // total: {
    //   handler (newValue, oldValue) {
    //     console.log('total==>',newValue)
    //     Reflect.set(this,'total',newValue)
    //     // console.log('total==>ok')
    //   }
    // },
  },
  mounted() {
    this.gettabledataFirst()
  },
  methods:{
    // 表头部重新渲染
    renderHeader ({ column, $index }) {
      // 新建一个 span
      const span = document.createElement('span')
      // 设置表头名称
      span.innerText = column.label
      // 临时插入 document
      document.body.appendChild(span)
      // 重点：获取 span 最小宽度，设置当前列，注意这里加了 20，字段较多时还是有挤压，且渲染后的 div 内左右 padding 都是 10，所以 +20 。（可能还有边距/边框等值，需要根据实际情况加上）
      column.minWidth = span.getBoundingClientRect().width + 80
      // 移除 document 中临时的 span
      document.body.removeChild(span)
      return column.label
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex%2 === 1) {
        return 'warning-row';
      } else if (rowIndex%2 === 0) {
        return 'success-row';
      }
      return '';
    },
    getRandomString(length) {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      const charactersLength = characters.length;
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
      }
      return result;
    },
    // download
    exportExcel() {
      // 将数据转换为工作表
      const worksheet = XLSX.utils.json_to_sheet(this.tableData);

      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      let name = this.getRandomString(8)
      // 导出Excel文件
      XLSX.writeFile(workbook, name+'.xlsx');
    },
    // 首次获得页面
    gettabledataFirst(){
      const star = this.currentPage
      const end = this.size
      console.log("star =====>",star)
      // console.log("end =====>",end)
      // this.tableData =
      if (this.apiKey === 'analysis_tf'){
        this.getAnalysisTFTable(this.searchKey,star,end)
      }
      if (this.apiKey === 'analysis_tf_chip-seq'){
        this.getAnalysisTFChipSeqTable(this.searchKey,star,end)
      }
      if (this.apiKey === 'analysis_tf_snv_alterating'){
        this.getAnalysisTFSnvAlteratingTable(this.searchKey,star,end)
      }
      if (this.apiKey === 'browse'){
        let tissue = this.searchKey.tissue
        let sampleType = this.searchKey.sampleType
        let chr = this.searchKey.chr
        this.getBrowseTable(tissue,sampleType,chr,star,end)
      }
    },
    // 更新分页
    handlePageChange(value){
      this.currentPage = value
      this.tableloading = true
      const star = this.currentPage
      const end = this.size
      if (this.apiKey === 'analysis_tf'){
        this.getAnalysisTFTable(this.searchKey,star,end)
      }
      if (this.apiKey === 'analysis_tf_chip-seq'){
        this.getAnalysisTFChipSeqTable(this.searchKey,star,end)
      }
      if (this.apiKey === 'analysis_tf_snv_alterating'){
        this.getAnalysisTFSnvAlteratingTable(this.searchKey,star,end)
      }
      if (this.apiKey === 'browse'){
        let tissue = this.searchKey.tissue
        let sampleType = this.searchKey.sampleType
        let chr = this.searchKey.chr
        this.getBrowseTable(tissue,sampleType,chr,star,end)
      }
      // this.tableData = this.tableAllData.slice(star,end)

    },
    //search
    searchTable(){
      // this.tableloading = true
      this.currentPage = 1
      const star = this.currentPage
      const end = this.size
      this.tableloading = true
          console.log("searchTable =====>",this.search)
      if (this.apiKey === 'analysis_tf'){
        let [tf,health_status,tissue,motif,snv,type] = [this.searchKey.tf,this.searchKey.health,this.searchKey.tissue,this.searchKey.motif,this.searchKey.snv,this.searchKey.type]
        api.analysis_tf.getTFSearch(tf,health_status,tissue,motif,star,end,snv,type,this.search).then(res => {
          console.log("res1 ==>",res)
          this.tableData =res.data.data
          this.total = res.data.data.length
          console.log("tableData =====>",this.tableData)
          this.tableloading = false
        })
      }
      if (this.apiKey === 'analysis_tf_chip-seq'){
        // form.tf,start,length,form.snv,form.type,form.health,form.tissue
        api.analysis_tf.getTFChipSeqBySearch(this.searchKey.tf,star,10,this.searchKey.snv,this.searchKey.type,this.searchKey.health,this.searchKey.tissue,this.search).then(res => {
          console.log("res1 ==>",res)
          this.tableData =res.data.data
          this.total = res.data.data.length
          console.log("tableData =====>",this.tableData)
          this.tableloading = false
        })
      }
      if (this.apiKey === 'analysis_tf_snv_alterating'){
        let [tf,health_status,tissue,motif,snv,type] = [this.searchKey.tf,this.searchKey.health,this.searchKey.tissue,this.searchKey.motif,this.searchKey.snv,this.searchKey.type]
        api.analysis_tf.getTFSnvAlteratingBySearch(tf,health_status,tissue,motif,star,end,snv,type,this.search).then(res => {
          console.log("res1 ==>",res)
          this.tableData =res.data.data
          this.total = res.data.data.length
          console.log("tableData =====>",this.tableData)
          this.tableloading = false
        })
      }
      if (this.apiKey === 'browse'){
        let tissue = this.searchKey.tissue
        let sampleType = this.searchKey.sampleType
        let chr = this.searchKey.chr
        api.Browse.getAllBySearch(tissue,sampleType,chr,this.search,star,end).then(res => {
          console.log("res1 ==>",res)
          this.tableData =res.data.data
          this.total = res.data.data.length
          console.log("tableData =====>",this.tableData)
          this.tableloading = false
        })
        // this.getBrowseTable(tissue,sampleType,chr,star,end)
      }
    },
  //   analysis tf
  //   表1
    getAnalysisTFTable(form,start,length){
      let [tf,health_status,tissue,motif,snv,type] = [form.tf,form.health,form.tissue,form.motif,form.snv,form.type]
      api.analysis_tf.getTF(tf,health_status,tissue,motif,start,length,snv,type).then(res => {
        console.log("res1 ==>",res)
        this.tableData =res.data.data
        this.total = res.data.recordsTotal
        console.log("tableData =====>",this.tableData)
        this.tableloading = false
      })
    },
    //   表3
    getAnalysisTFChipSeqTable(form,start,length){
      api.analysis_tf.getTFChipSeq(form.tf,start,length,form.snv,form.type,form.health,form.tissue).then(res => {
        console.log("res3 ==>",res)
        this.tableData =res.data.data
        this.total = res.data.recordsTotal
        console.log("tableData3 =====>",this.tableData)
        this.tableloading = false
      })
    },
    //   表2
    getAnalysisTFSnvAlteratingTable(form,start,length){
      let [tf,health_status,tissue,motif,snv,type] = [form.tf,form.health,form.tissue,form.motif,form.snv,form.type]
      api.analysis_tf.getTFSnvAlterating(tf,health_status,tissue,motif,start,length,snv,type).then(res => {
          console.log("res2 =====>",res)
          this.tableData =res.data.data
          this.total = res.data.recordsTotal
          this.tableloading = false
      })
    },
    getBrowseTable(tissue,sampleType,chr,start,length){
      api.Browse.getAll(tissue,sampleType,chr,start,length).then(res => {
        console.log(res)
        this.tableData = res.data.data
        this.total = res.data.recordsTotal
        this.tableloading = false
        // console.log("data.table.tableData=>",data.table.tableData)
      })
    }
  },
  setup(){
    const router = useRouter()
    const route = useRoute()


    const toDetail = (ASMID,snv)=>{
      router.push({
        path:"/detail",
        query:{
          ASMID,
          snv
        }
      })
    }

    return {
      toDetail,
      route
    }
  }
}
</script>

<style scoped>
::v-deep .el-table .warning-row {
  background: white;
  font-size: 15px
}

::v-deep .el-table .success-row {
  background: white;
  font-size: 15px
}
::v-deep .table-header-row .table-header-cell{
  background-color: #eeeeee;
}
::v-deep .table-header-row .table-header-cell .cell{
  /*White-space:nowrap;*/
}
</style>
